<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" size="small">
        <el-form-item prop="params.commodityName">
          <el-input
            v-model="queryParams.params.commodityName"
            class="filter-item"
            clearable
            placeholder="商品名称"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item prop="params.customCode">
          <el-input
            v-model="queryParams.params.customCode"
            class="filter-item"
            clearable
            placeholder="自编码"
            style="width: 150px;"
          />
        </el-form-item>
        <!-- 按钮 -->
        <el-button
          v-permission="['/store/stock/search']"
          v-waves
          class="filter-item"
          icon="el-icon-search"
          size="small"
          style="margin-left: 10px;"
          type="primary"
          @click="getDataList"
        >查询
        </el-button>
        <el-button
          v-permission="['/store/stock/add']"
          v-waves
          class="filter-item"
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="handleOpenDialog('add')"
        >新增
        </el-button>
        <el-button
          v-permission="['/store/stock/search']"
          v-waves
          class="filter-item"
          icon="el-icon-refresh"
          size="small"
          type="primary"
          @click="resetQueryForm"
        >重置
        </el-button>
      </el-form>
    </div>
    <!-- 数据表格 -->
    <el-table
      v-loading="dataListLoading"
      :data="dataList"
      border
      fit
      highlight-current-row
      size="small"
      style="width: 100%;"
      @sort-change="handleSortChange"
    >
      <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
      <el-table-column align="center" label="商品名称" prop="commodityName" show-overflow-tooltip />
      <el-table-column align="center" label="自编码" prop="customCode" show-overflow-tooltip />
      <el-table-column align="center" label="库存数量" prop="quantity" show-overflow-tooltip sortable>
        <template slot-scope="scope">
          <el-tooltip class="item" content="点击可以调整库存" effect="dark" placement="top">
            <el-link
              type="primary"
              @click="openStockChangeDialog(scope.row)"
            >
              {{ scope.row.quantity }}{{ scope.row.unit }}
            </el-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="成本价" prop="costPrice" show-overflow-tooltip sortable />
      <el-table-column align="center" label="销售价" prop="salePrice" show-overflow-tooltip sortable>
        <template slot-scope="scope">
          <el-tooltip class="item" content="点击可以售价" effect="dark" placement="top">
            <el-link
              type="primary"
              @click="handleStockPriceChange(scope.row)"
            >
              {{ scope.row.salePrice }}元
            </el-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建人" prop="creatorName" show-overflow-tooltip />
      <el-table-column align="center" label="创建时间" prop="createdDate" show-overflow-tooltip sortable />
      <el-table-column align="center" label="编辑时间" prop="modifiedDate" show-overflow-tooltip sortable />
      <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip />
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            v-permission="['/store/stock/search']"
            v-waves
            size="mini"
            type="primary"
            @click="handleOpenDialog('change',scope.row)"
          >变更记录
          </el-button>
          <el-button
            v-permission="['/store/stock/delete']"
            v-waves
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.size"
        :page-sizes="[10,20,30, 50]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增-编辑对话框 -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      element-loading-text="保存中"
      width="50%"
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        label-position="left"
        label-width="150px"
        size="small"
      >
        <el-row :gutter="20">
          <el-divider content-position="center"><i class="el-icon-s-help">商品信息</i></el-divider>
          <el-col :span="6">
            <el-form-item label="商品名称：" label-width="20" prop="commodityId">
              <el-select
                v-model="dataForm.commodityId"
                :disabled="dialogStatus !== 'add'"
                :loading="fuzzyQueryLoading"
                :remote-method="getCommodityListByKeyword"
                clearable
                filterable
                placeholder="名称/条码/自编码"
                remote
                reserve-keyword
                style="width: 100%;"
                @change="handleCommodityChange"
              >
                <el-option v-for="item in commodityList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="自编码：" label-width="20" prop="customCode">
              <el-input v-model="dataForm.customCode" placeholder="自编码" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="成本价：" label-width="20" prop="costPrice">
              <el-input v-model="dataForm.costPrice" placeholder="成本价" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售价：" label-width="20" prop="salePrice">
              <el-input v-model="dataForm.salePrice" placeholder="销售价" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-divider content-position="center"><i class="el-icon-truck" /> 库存信息</el-divider>
          <el-col :span="12">
            <el-form-item label="增加数量：" label-width="20" prop="quantity">
              <el-input v-model="dataForm.quantity" placeholder="增加数量" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：" label-width="20" prop="remark">
              <el-input
                v-model="dataForm.remark"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="备注"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus==='add'" size="small" type="primary" @click="handleAdd">确定</el-button>
        <el-button v-if="dialogStatus==='update'" size="small" type="primary" @click="handleUpdate">确定</el-button>
      </div>
    </el-dialog>
    <!-- 变更记录   -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="changeFormVisible"
      element-loading-text="保存中"
      width="60%"
    >
      <el-form ref="changeForm" :inline="true" :model="changeParams" size="small">
        <el-table
          v-loading="dataListLoading"
          :data="changeDataList"
          border
          fit
          highlight-current-row
          size="small"
          style="width: 100%;"
        >
          <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
          <el-table-column align="center" label="商品名称" prop="commodityName" show-overflow-tooltip />
          <el-table-column align="center" label="入库前数量" prop="beforeQuantity" show-overflow-tooltip />
          <el-table-column align="center" label="入库数量" prop="quantity" show-overflow-tooltip />
          <el-table-column align="center" label="入库后数量" prop="afterQuantity" show-overflow-tooltip />
          <el-table-column align="center" label="成本价" prop="costPrice" show-overflow-tooltip />
          <el-table-column align="center" label="金额小计" prop="totalAmount" show-overflow-tooltip />
          <el-table-column align="center" label="入库时间" prop="inDate" show-overflow-tooltip />
          <el-table-column align="center" label="业务场景" prop="sceneName" show-overflow-tooltip />
          <el-table-column align="center" label="创建人" prop="creatorName" show-overflow-tooltip />
          <el-table-column align="center" label="调整原因" prop="remark" show-overflow-tooltip />
        </el-table>
      </el-form>
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="changeParams.page"
          :page-size="changeParams.size"
          :page-sizes="[10,20,30, 50]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleChangeSizeChange"
          @current-change="handleChangeCurrentChange"
        />
      </div>
    </el-dialog>
    <!-- 调库存弹出框 -->
    <el-dialog
      :before-close="handleStockChangeDialogClose"
      :visible.sync="stockChangeDialogVisible"
      title="调库存"
      width="30%"
    >
      <!-- 商品名称 -->
      <el-form
        ref="stockChangeForm"
        :model="stockChangeForm"
        :rules="changeRules"
        label-position="left"
        label-width="150px"
        size="small"
      >
        <div class="stock-change-form-title">商品名称：{{ currentRow ? currentRow.commodityName : '' }} |
          库存数量：{{ currentRow ? currentRow.quantity : '' }}
        </div>
        <el-form-item label="业务场景：" prop="scene">
          <el-select
            v-model="stockChangeForm.scene"
            clearable
            placeholder="积分加钱兑换"
            style="width: 100%"
          >
            <el-option
              v-for="item in stockSceneList"
              :key="item.id"
              :label="item.value"
              :value="parseInt(item.code)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调整数量：" prop="quantity">
          <el-input v-model="stockChangeForm.quantity" type="number" />
        </el-form-item>
        <el-form-item label="调整原因：" prop="remark">
          <el-input v-model="stockChangeForm.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleStockChangeDialogClose">取 消</el-button>
        <el-button size="small" type="primary" @click="handleConfirmStockChange">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { add, del, fetchList, update, updateSalePrice } from '@/api/store/stock'
import { add as detailAdd, fetchList as fetchDetailList } from '@/api/store/stockDetail'
import { fuzzyQuery } from '@/api/store/commodity'
import { typeList } from '@/api/system/dict'

export default {
  name: 'Online',
  data() {
    return {
      total: 0,
      dataList: [],
      changeDataList: [],
      commodityList: [],
      stockSceneList: [],
      quantity: 0,
      dataListLoading: true,
      dialogFormVisible: false,
      fuzzyQueryLoading: false,
      dialogLoading: false,
      stockChangeDialogVisible: false,
      changeFormVisible: false,
      dialogStatus: '',
      currentRow: {},
      dialogTitleMap: {
        add: '新增',
        update: '编辑',
        change: '变更记录'
      },
      // 查询参数对象
      queryParams: {
        page: 1,
        size: 10,
        params: {
          commodityName: '',
          customCode: ''
        }
      },
      changeParams: {
        page: 1,
        size: 10,
        params: {
          commodityId: ''
        }
      },
      dataForm: {
        commodityId: '',
        customCode: '',
        costPrice: '',
        salePrice: '',
        quantity: '',
        remark: ''
      },
      stockChangeForm: {
        scene: 0,
        quantity: '',
        beforeQuantity: '',
        remark: ''
      },
      rules: {
        commodityId: [{ required: true, message: '商品名称不能为空', trigger: 'change' }],
        customCode: [{ required: true, message: '自编码不能为空', trigger: 'change' }],
        quantity: [{ required: true, message: '增加数量不能为空', trigger: 'change' }]
      },
      changeRules: {
        quantity: [{ required: true, message: '调整数量不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    formReadOnly() {
      return this.dialogStatus === 'view'
    }
  },
  mounted() {
    this.getDataList()
    typeList({ type: 'stockScene' }).then(res => {
      this.stockSceneList = res.data
    })
  },
  methods: {
    shownIndex(index) {
      return (this.queryParams.page - 1) * this.queryParams.size + index + 1
    },
    handleSortChange(data) {
      console.log('handleSortChange')
      console.log(data)
      if (data.order) {
        if (data.order.indexOf('asc') > -1) {
          this.queryParams.sortOrder = 'asc'
        } else {
          this.queryParams.sortOrder = 'desc'
        }
        this.queryParams.sortName = data.prop
      }
      console.log(this.queryParams)
      this.getDataList()
    },
    // 手动重置表单
    resetDataForm() {
      if (this.$refs['dataForm']) {
        // 由于编辑数据的时候会导致表单对象的初始化值发生变更，所以在重置表单前先手动重置表单对象的值
        this.dataForm = {
          commodityId: '',
          customCode: '',
          costPrice: '',
          salePrice: '',
          quantity: '',
          remark: ''
        }
        this.$refs['dataForm'].resetFields()
      }
      if (this.$refs['stockChangeForm']) {
        this.stockChangeForm = {
          scene: 0,
          quantity: '',
          remark: ''
        }
        this.$refs['stockChangeForm'].resetFields()
      }
    },
    resetQueryForm() {
      this.$refs['queryForm'].resetFields()
      this.$refs['stockChangeForm'].resetFields()
      this.queryParams.page = 1
      this.getDataList()
    },
    getDataList() {
      this.dataListLoading = true
      fetchList(this.queryParams)
        .then(res => {
          console.log(res)
          this.dataList = res.data.records
          this.total = res.data.total
          this.dataListLoading = false
          this.$message.success(res.msg || '获取数据成功')
        })
        .catch(err => {
          console.log(err)
          this.dataListLoading = false
        })
    },
    getChangeData() {
      this.dataListLoading = true
      this.changeParams.params.commodityId = this.currentRow.commodityId
      fetchDetailList(this.changeParams).then(res => {
        console.log(res)
        this.changeDataList = res.data.records
        this.total = res.data.total
        this.dataListLoading = false
        this.$message.success(res.msg || '获取数据成功')
      }).catch(err => {
        console.log(err)
        this.dataListLoading = false
      })
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.getDataList()
    },
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getDataList()
    },
    handleChangeSizeChange(size) {
      this.queryParams.size = size
      this.getDataList()
    },
    handleChangeCurrentChange(page) {
      this.queryParams.page = page
      this.getDataList()
    },
    handleOpenDialog(type, rowData) {
      // 表单状态为新增/编辑、打开新增/编辑窗口
      this.resetDataForm()
      this.dialogStatus = type
      if (type === 'add') {
        this.dialogFormVisible = true
      } else {
        this.changeFormVisible = true
        this.currentRow = JSON.parse(JSON.stringify(rowData))
        this.getChangeData()
      }
    },
    handleAdd() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          add(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '新增成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleUpdate() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          update(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '修改成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleDelete(rowData) {
      this.$confirm('是否删除该记录？', '删除提示', { type: 'warning' })
        .then(() => {
          del(rowData.id)
            .then(res => {
              console.log(res)
              // this.$message.success(res.msg || '删除成功')
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(cancel => {
          console.log(cancel)
        })
    },
    dateChangeHandler(value) {
      if (value) {
        this.dataForm.startDate = value[0]
        this.dataForm.endDate = value[1]
      }
    },
    // 模糊查询商品列表
    getCommodityListByKeyword(query) {
      console.log('getCommodityListByKeyword')
      console.log(query)
      if (query) {
        this.fuzzyQueryLoading = true
        setTimeout(() => {
          fuzzyQuery(query).then(res => {
            console.log(res)
            this.commodityList = res.data
            this.fuzzyQueryLoading = false
          }).catch(err => {
            console.log(err)
            this.fuzzyQueryLoading = false
          })
        }, 300)
      } else {
        this.commodityList = []
      }
    },
    handleCommodityChange(commodityId) {
      console.log(commodityId)
      const tmpList = this.commodityList.filter(item => item.id === commodityId)
      if (tmpList.length === 1) {
        this.dataForm.salePrice = tmpList[0].salePrice
        this.dataForm.customCode = tmpList[0].customCode
        this.dataForm.costPrice = tmpList[0].costPrice
      }
    },
    openStockChangeDialog(rowData) {
      console.log('openStockChangeDialog')
      console.log(rowData)
      this.currentRow = JSON.parse(JSON.stringify(rowData))
      this.stockChangeDialogVisible = true
    },
    handleStockChangeDialogClose() {
      console.log('handleStockChangeDialogClose')
      this.stockChangeDialogVisible = false
      this.resetDataForm()
    },
    handleStockPriceChange(rowData) {
      const params = JSON.parse(JSON.stringify(rowData))
      this.$prompt('请修改销售价格', '调整商品售价', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'number',
        inputValue: params.salePrice,
        inputErrorMessage: '数字格式不正确'
      }).then(({ value }) => {
        // 调用dispatch更新数量
        if (value && value > 0) {
          params.salePrice = value
          updateSalePrice(params).then(res => {
            console.log(res)
            this.$message.success(res.msg || '调整价格成功！')
            this.getDataList()
          }).catch(err => {
            console.log(err)
            this.$message.error(err || '操作失败')
          })
        } else {
          this.$message.warning('数量不能小于0！')
        }
      }).catch(() => {
        console.log('取消输入')
      })
    },
    handleConfirmStockChange() {
      // 先进行表单校验
      this.$refs['stockChangeForm'].validate(valid => {
        if (valid) {
          this.stockChangeForm.commodityId = this.currentRow.commodityId
          this.stockChangeForm.beforeQuantity = this.currentRow.quantity
          detailAdd(this.stockChangeForm).then(res => {
            this.$message.success(res.msg || '新增成功')
            this.stockChangeDialogVisible = false
            this.resetDataForm()
            this.getDataList()
          })
        }
      })
    }
  }
}
</script>
<style scoped>

.el-form-item {
  margin-bottom: 30px;
}

.el-form .el-select {
  width: 100%;
}

.stock-change-form-title {
  width: 100%;
  text-align: center;
  font-weight: bold;
  font-size: 1rem;
  margin-bottom: 20px;
}

</style>
